package com.zyf.chapter01.principle.SOLID.OCP;


import com.zyf.chapter01.principle.SOLID.OCP.handler.AlertHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * 使用内部类的形式，迭代告警类的需求
 * @author yifeng
 */
public class Alert {

    /**
     * 最初的需求
     * 监控告警案例
     */
    class FirstAlert {
        private AlertRule rule;
        private Notification notification;
        public FirstAlert(AlertRule rule, Notification notification) {
            this.rule = rule;
            this.notification = notification;
        }

        public void check(String api,
                          long requestCount,
                          long errorCount, long durationOfSeconds) {
            long tps = requestCount / durationOfSeconds;
            // TPS超过预设置最大值，则通知负责人或团队
            if(tps > rule.getMatchedRule(api).getTps()) {
                notification.notify(NotificationEmergencyLevel.URGENCY, "...");
            }
            // 接口错误次数超过允许的最大值，则通知负责人或团队
            if(errorCount > rule.getMatchedRule(api).getMaxErrorCount()) {
                notification.notify(NotificationEmergencyLevel.SEVERE, "...");
            }
        }
    }
    /**
     *  增加需求，每秒钟接口超时请求个数，超过某个预先设置的最大阈值时，我们也要触发告警发送通知
     * 监控告警案例
     */
    public class IncreaseAlert{

        private AlertRule rule;
        private Notification notification;

        public IncreaseAlert(AlertRule rule, Notification notification) {
            this.rule = rule;
            this.notification = notification;
        }

        // 改动一:添加参数timeoutCount
        public void check(String api,
                          long requestCount,
                          long errorCount,
                          long durationOfSeconds, long timeoutCount) {
            long tps = requestCount / durationOfSeconds;
            // TPS超过预设置最大值，则通知负责人或团队
            if(tps > rule.getMatchedRule(api).getTps()) {
                notification.notify(NotificationEmergencyLevel.URGENCY, "...");
            }
            // 接口错误次数超过允许的最大值，则通知负责人或团队
            if(errorCount > rule.getMatchedRule(api).getMaxErrorCount()) {
                notification.notify(NotificationEmergencyLevel.SEVERE, "...");
            }
            // 改动二：添加接口超时处理逻辑
            long timeoutTps = timeoutCount / durationOfSeconds;
            if (timeoutTps > rule.getMatchedRule(api).getMaxTimeoutTps()) {
                notification.notify(NotificationEmergencyLevel.URGENCY, "...");
            }
        }
    }

    /**
     * 重构FirstAlert的代码，使其扩展性更好一些
     * 监控告警案例
     */
    public class RefactorFirstAlert {
        private List<AlertHandler> alertHandlers = new ArrayList<>();

        public void addAlertHandler(AlertHandler alertHandler) {
            this.alertHandlers.add(alertHandler);
        }

        public void check(ApiStatInfo apiStatInfo) {
            for (AlertHandler handler : alertHandlers) {
                handler.check(apiStatInfo);
            }
        }
    }
}